<template>
     <el-card class="card_box">
        <div class="basic-flex">
            <div>
                <el-link type="primary" v-for="item in titleList" :key="item.title" @click="changeInfo({value:item.title,url:item.url})" :class="activeName==item.title?'selected-tab-style tab-title':'tab-style  tab-title'">{{ item.title }}</el-link>
            </div>
            <div class="align-center">
                <el-button link type="primary" @click="goTo('/users/usersData')">
                    《返回
                </el-button>
            </div>
        </div>
    </el-card>
    <el-row :gutter="10">
        <el-col :span="8">
           <el-card style="height: 296px;" >
            <div style="padding: 20px;">
                <div class="basic-flex">
                    <div class="title">会员消费</div>
                    <div><img :src="getAssetsFile('images/users/consume.svg')" style="width: 100%;"/></div>
                </div>
                <el-row >
                    <el-col :span="12" style="text-align:center;">
                        <el-statistic :value="info.member_consumption.all_orders"></el-statistic>
                        <div class="footer">累计订单数</div>
                    </el-col>
                    <el-col :span="12" style="text-align:center;">
                        <el-statistic :value="info.member_consumption.all_sales">
                            <template #prefix>￥</template>
                        </el-statistic>
                        <div class="footer">总消费金额</div>
                    </el-col>
                    <el-col :span="12" style="text-align:center;padding-top:50px">
                        <el-statistic :value="info.member_consumption.day_sales">
                            <template #prefix>￥</template>
                        </el-statistic>
                        <div class="footer">日消费额</div>
                    </el-col>
                    <el-col :span="12" style="text-align:center;padding-top:50px">
                        <el-statistic :value="info.member_consumption.other_sales"></el-statistic>
                        <div class="footer">其他商品营业额</div>
                    </el-col>
                </el-row> 
       
            </div>
                
           </el-card>
        </el-col>
        <el-col :span="8">
            <el-card>
                <div class="chart-style">
                <div class="title"> 会员和非会员占比</div>
                <div id="memberPre" style="width:auto;height: 200px"></div>
            </div>
            </el-card>
            
        </el-col>
        <el-col :span="8">
            <el-card>
                <div class="chart-style">
                <div class="title"> 使用套餐期限</div>
                <div id="orders" style="width:auto;height: 200px"></div>
            </div>
            </el-card>
        </el-col>
    </el-row>
    <el-row :gutter="10" style="margin-top: 10px;">
        <el-col :span="8">
            <el-card>
                <div class="chart-style">
                <div class="title"> 用户性别比例</div>
                <div id="memberSex" style="width:auto;height: 200px"></div>
            </div>
            </el-card>
        </el-col>
        <el-col :span="8">
            <el-card>
                <div class="chart-style">
                    <div class="title"> 用户年龄占比</div>
                    <div id="memberAge" style="width:auto;height: 200px"></div>
                </div>
            </el-card>
        </el-col>
        <el-col :span="8">
            <el-card>
                <div class="chart-style">
                    <div class="title"> 用户端别占比</div>
                    <div id="memberPlat" style="width:auto;height: 200px"></div>
                </div>
            </el-card>
        </el-col>
    </el-row>

    <el-card style="margin-top: 20px;">
        <div class="title font-medium">商品消费</div>
        <el-divider></el-divider>
        <div class="table-style">
            <div style="text-align: right;width: 100%;">
                <el-link v-for="(item,index) in orderTypeList"
                :underline="false"
                :key="item.title"
                :class="currentTitle==item.title?'selected':'unselected'"
                @click="changeTitle({title:item.title,index})">{{ item.title }}</el-link>
            </div>
            <div class="padding-top-14">
                <el-table :data="tableList" border :header-cell-style="tableHeader" :cell-style="{color:'#333333'}">
                    <el-table-column v-for="item in columns" 
                    :key="item.title" :border="true" 
                    :prop="item.key" 
                    :label="item.title"
                    :formatter="formatter"
                    header-align="center"
                    align="center"></el-table-column>
                </el-table>
            </div>
        </div>
    </el-card>
</template>
<script setup lang="ts">
import "@/style/modules/users.scss";
import {consumePath,orderConsumePath} from "@/config/paths";
import * as echarts from 'echarts';
import {getAssetsFile} from "@/utils";
import {goTo} from "@/utils/users/pubFun" 

import {tableHeader} from '@/utils/users/pubConfig'
const titleList=ref<{title:string,url:string}[]>([
    {title:'会员增长分析',url:'/users/usersAnalyse'},
    {title:'会员消费分析',url:'/users/userConsume'}
])
type EChartsOption = echarts.EChartsOption;
interface ConsumeInfo{
    member_consumption:{
        all_orders:number,
        all_sales:number,
        day_sales:number,
        other_sales:number
    },
    member_proportion:{text:string,value:number}[],
    order_usage_period:{text:string,value:number}[],
    member_gender_proportion:{text:string,value:number}[],
    member_platform_proportion:{text:string,value:number}[],
    member_age_proportion:{text:string,value:number}[]
}
const info=ref<ConsumeInfo>({
    member_consumption:{
        all_orders:0,
        all_sales:0,
        day_sales:0,
        other_sales:0
    },
    member_proportion:[{
        text:'',value:0
    }],
    order_usage_period:[{
        text:'',value:0
    }],
    member_gender_proportion:[{
        text:'',value:0
    }],
    member_platform_proportion:[{
        text:'',value:0
    }],
    member_age_proportion:[{
        text:'',value:0
    }]

})
const activeName=ref<string>('会员消费分析')
function changeInfo({value,url}:{value:string,url:string}){
    // console.log('url',url)
    activeName.value =value
    goTo(url)
}

const orderTypeList=[{title:'长租套餐'},{title:'短租套餐'}]
const currentTitle=ref<string>('长租套餐')
interface Order{
    rank:number,
    all_sales_num:number,
    all_sales_price:number,
    order_name:string,
    repurchase_rate:number
}
interface Orders{
    long_rent_orders ?:Order[],
    short_rent_orders ?:Order[]
}
interface Column{
    key:string,
    title:string,
    dataKey:string,
    width ?:string
    class ?:string
}
const columns=ref<Column[]>([
    {key:'rank', title:'排行',dataKey:'rank'},
    {key:'order_name',title:'套餐名称',dataKey:'order_name'},
    {key:'all_sales_num',title:'销量',dataKey:'all_sales_num'},
    {key:'all_sales_price',title:'销量金额',dataKey:'all_sales_price'},
    {key:'repurchase_rate',title:'复购率',dataKey:'repurchase_rate'}
])
const tableList=ref<Order[]>([])
onMounted(async()=>{
tableList.value=[]
   const newData = await consumeInfo()
   const {long_rent_orders} =await orderConsumeInfo()
   tableList.value.push(...long_rent_orders)
    info.value=newData
    const memberChart = echarts.init(document.getElementById('memberPre'));
    const memberPro:EChartsOption=formatMemberPro()
    memberChart.setOption(memberPro)
    const orderChart = echarts.init(document.getElementById('orders'));
    const orderPro:EChartsOption=formatOrders()
    orderChart.setOption(orderPro)
    const  memberSexChart = echarts.init(document.getElementById('memberSex'));
    const memberSexPro:EChartsOption=fromatSex()
    memberSexChart.setOption(memberSexPro)
    const  memberAgeChart = echarts.init(document.getElementById('memberAge'));
    const memberAgePro:EChartsOption=formatAge()
    memberAgeChart.setOption(memberAgePro)
    const  memberPlatChart = echarts.init(document.getElementById('memberPlat'));
    const memberPlatPro:EChartsOption=formatPlat()
    memberPlatChart.setOption(memberPlatPro)
    window.addEventListener("resize", () => {
        memberChart.resize();
        orderChart.resize();
        memberSexChart.resize();
        memberAgeChart.resize();
        memberPlatChart.resize();
      });
})
async function consumeInfo(){

    const {data}=await baseRequest.get(consumePath.value)
    return data
}
async function orderConsumeInfo() {
 
    const {data}=await baseRequest.get(orderConsumePath.value)
    return data
}
const formatter = (row: Order, column: any) => {
  if(column.property=='repurchase_rate'){
        // console.log('column',column)
        return Number(row.repurchase_rate*100).toFixed(2)+'%'
  }
  return row[column.property]

}
//设置会员与非会员图表
function formatMemberPro(){
    const {member_proportion}=info.value
    let sourceDataX=['category']
    let sourceDataY:Array<string|number>=['']
    let list:{name:string,value:number}[]=[{name:'',value:0}]
    let total=0
    member_proportion.forEach(item=>{
        sourceDataX.push(item.text)
        sourceDataY.push(item.value)
        // list[item.text]=item.value
        list.push({name:item.text,value:item.value})
        total +=item.value
    })
    let option
    option ={
        legend: {
            orient:'vertical',
            // align:'left',
            type: 'scroll',
            right: '20',
            top:'60',
            icon:'diamond',
            itemWidth:12,
            itemHeight:12,
            formatter:(name)=>{
                const value = list.filter(item=>(item.name==name))[0].value
                const pre=Number(value/total*100).toFixed(2)
                return `${name} ${pre}%`
            }
        },
        tooltip: {},
        grid:[{right:'100%',bottom:'0',left:'30%'}],
        dataset: {
            source: [
               sourceDataX,
               sourceDataY 
            ]
        },
        xAxis: [
            { 
                type: 'category', 
                show:false
            }
        ],
        yAxis: [{show:false}],
        series: [
            // These series are in the first grid.
            { 
                type: 'bar', 
                color:'#97EEFF',
                barWidth:'40', 
                // 柱状图上方文本标签，默认展示数值信息
                label:{
                    show: false,
                    position: "top"
                } 
            },
            { 
                type: 'bar',
                color:'#00B4D8',
                barWidth:'40', 
                label:{
                    show: false,
                    position: "top"
                } 
            },
            
        ]
    }
    return option
}
//设置套餐使用期限
function formatOrders(){
    const {order_usage_period}=info.value
    // console.log('order_usage_period',order_usage_period)
    const seriesData:{name:string,value:number}[]=[]
    let yData:number[]=[]
    let total=0
    order_usage_period.forEach(item=>{
        seriesData.push({name:item.text,value:item.value})
        yData.push(item.value)
        total +=item.value
    })
     //显示单个label
    //  let label={show:true,position:'inside',formatter:`{d}%`,}
    // let labelLine={show:true}
    // seriesData.forEach(item=>{
    //     if(item.value==Math.max(...yData)){
    //         item['label']=label
    //         item['labelLine']=labelLine
    //     }
    // })
    return {
        legend: {
            orient:'vertical',
            // align:'left',
            type: 'scroll',
            right: '10',
            top:'60',
            // formatter:(name)=>{
            //     const value = seriesData.filter(item=>item.name == name)[0].value
            //     const pre =Number(value/total*100).toFixed(2)
            //     return `${name} ${pre}%`
            // }
        },
        tooltip: {
            trigger: 'item',
            formatter: '{b} : {c} ({d}%)'
        },
        color:['#97EEFF','#01B3D7','#0077B6','#03045E'],
        series:[
            {
                label:false,
                type:'pie',
                center: ['30%', '55%'],
                radius: [40, 80],
                // roseType:'radius',
                // bottom:'0',
                data:seriesData}
        ]
    } 
}
//设置用户性别占比
function fromatSex(){
    const {member_gender_proportion}=info.value
    const seriesData:{name:string,value:number}[]=[] 
    let total=0
    member_gender_proportion.forEach(item=>{
        seriesData.push({name:item.text,value:item.value})
        total+= item.value
    })
    return {
        legend: {
            orient:'vertical',
            // align:'left',
            type: 'scroll',
            right: '10',
            top:'60',
            icon:'roundRect',
            itemWidth:10,
            itemHeight:10,
            formatter:(name)=>{
                const value = seriesData.filter(item=>item.name == name)[0].value
                const pre =Number(value/total*100).toFixed(2)
                return `${name} ${pre}%`
            }
        },
        tooltip:{
            formatter:`{b}:{c}`
        },
        color:['#00B4D8','#97EEFF'],
        series:[
            {
                type:'pie',
                center: ['30%', '55%'],
                radius: [40, 80],
                // bottom:'0',
                label: {
                    show: false
                },
                data:seriesData
            }
        ]
    }

}
//设置年龄占比
function formatAge(){
    const {member_age_proportion}=info.value
    let xData:string[]=[]
    let yData:number[]=[]
    let list:{name:string,value:number}[]=[{name:'',value:0}]
    let total=0
   
    member_age_proportion.forEach(item=>{
        xData.push(item.text)
        yData.push(item.value)
        list.push({name:item.text,value:item.value})
        total +=item.value
    })
    
    // console.log(xData)
    return {
        legend:{
            orient:'vertical',
            // align:'left',
            type: 'scroll',
            right: '50',
            top:'60',
        },
        xAxis:{
            // data:xData,
            show:false,
           
        },
        yAxis: {
            data:xData,
            show:false,
            axisLabel:{
                interval:0,//横向信息全部显示,
                textStyle:{
                    align:'left'
                }
            },
            
        },
        grid:[{bottom:'0',right:'100%',top:'20%',left:'90%'}],
        series:[{
            data:yData,
            type:'bar',
            barWidth:'12px',
            label:{
                show:true,
                formatter:`{b}`,
                position:'insizeLeft',
                color:'rgba(102, 102, 102, 1)',
                offset:[0,-20],
                textStyle:{
                    colort:'#999999'
                }
                
            },
            itemStyle:{
                borderRadius:10,
                color:(params)=>{
                    const colorList=['#97EEFF','#25CCED','#00B4D8','#0077B6']
                    return colorList[params.dataIndex]
                }
            }
        },
        {
            data:yData,
            type:'bar',
            barWidth:'12px',
            label:{
                position:'right',
                show:true,
                formatter:({value})=>{
                    // console.log('value',value)
                  return Number(value/total*100).toFixed(2) +'%'
                }
            },
            barGap:'-100%',
            z:'-1',
            itemStyle:{
                borderRadius:10,
                color:(params)=>{
                    const colorList=['#97EEFF','#25CCED','#00B4D8','#0077B6']
                    return colorList[params.dataIndex]
                }
            }
        }
    ]
    }
}
//设置用户端占比{}
function formatPlat(){
    const {member_platform_proportion}=info.value
    let xData:string[]=['category']
    let yData:Array<string|number>=['']
    let list:{name:string,value:number}[]=[{name:'',value:0}]
    let total=0
    member_platform_proportion.forEach(item=>{
        xData.push(item.text)
        yData.push(item.value)
        list.push({name:item.text,value:item.value})
        total += item.value
    })
    return {
        legend:{
            data:xData,
            icon:'diamond',
            top:'50',
            itemWidth:12,
            itemHeight:12,
            formatter:(name)=>{
                const value = list.filter(item=>(item.name==name))[0].value
                const pre=Number(value/total*100).toFixed(2)
                return `${name} ${pre}%`
            }
        },
        tooltip:{
         
        },
        xAxis:
        { 
            type: 'value',
            show:false
        },
        yAxis: [
            {
                type:'category',
                show:false
            }
        ],
        dataset: {
            source: [xData,yData]
        },
        grid:[{right:'100%',bottom:'0',top:'60%',left:'100%'}],
        series: [
            // These series are in the first grid.
            { 
                type: 'bar', 
                color:'#97EEFF',
                barWidth:'40',
                barGap:"-100%",
            // 柱状图上方文本标签，默认展示数值信息
                label:{
                    show: false,
                    position: "top"
             } 
            },
            { type: 'bar',
                color:'#00B4D8',
                barWidth:'40',
                label:{
                    show: false,
                    position: "top"
                } 
            },
           
        ]
    }
}
//点击切换套餐
async function changeTitle({title,index}:{title:string,index:number}){
    tableList.value=[]
    currentTitle.value=title
    const { long_rent_orders,short_rent_orders} =await orderConsumeInfo()
    if(index){
        tableList.value.push(...short_rent_orders)
        return
    }
    tableList.value.push(...long_rent_orders)

}
</script>

<style scoped lang="scss">
.footer{
    color:#666666
}
.el-statistic {
  --el-statistic-content-font-size: 18px;
  --el-statistic-content-color:#00B4D8;
  --el-statistic-content-font-weight:500;
}
.chart-style{
    padding:24px 7px 32px 33px;
    background-color: #ffffff;
    height: 200px;
}
.el-divider--horizontal{
    margin:12px 0;
}
.table-style{
    padding: 16px 32px 38px 32px;
    text{
        padding:6px 26px;
        border-radius: 3px;
        font-weight: 500;
    }
}

</style>